const { BrowserWindow } = require('electron');
const program = require("../common/program");
const db = require("../database");
const { execShell } = require("../utils/shell");

class Decorater {
  constructor(fn_b = null, fn_a = null) {
    this.fn_b = fn_b;
    this.fn_a = fn_a;
  }
  dec(fn) {
    return (arg) => {
      this.fn_b && this.fn_b(arg);
      fn(arg);
      this.fn_a && this.fn_a(arg);
    }
  }
};

Dec = new Decorater((...arg) => {
  if (program.timer) clearInterval(program.timer);
  if (program.shellChild.length) {
    program.shellChild.forEach(item => {
      item.kill("SIGINT");
    });
    program.shellChild = [];
  }
  const userDefineShell = db.get('userDefineShell').value();
  let index = userDefineShell.findIndex(item => item.label == arg[0].label);
  let window = BrowserWindow.getFocusedWindow();
  window && window.webContents.send("change-active-shell", index);
  program.appTrayActiveMenu = index;
});

let shellMenuDefaultController = Dec.dec(_ => {
  program.appTray.setTitle("\u001b[34m " + "bongo cat" + "\x1B[0m");
});

let getShellMenuController = (item) => {
  return Dec.dec(_ => {
    // console.log(item);
    program.appTray.setToolTip(item.tooltip);
    if (item.isLoop) {
      program.timer = setInterval(_ => {
        program.shellChild.push(execShell(item, program.appTray));
      }, item.loopDuration);
    } else {
      program.shellChild.push(execShell(item, program.appTray));
    }
  });
};

module.exports = {
  shellMenuDefaultController,
  getShellMenuController
}